<template>
    <!-- 对话框表单 -->
    <!-- 建议使用 Prettier 格式化代码 -->
    <!-- el-form 内可以混用 el-form-item、FormItem、ba-input 等输入组件 -->
    <el-dialog
    custom-class="ba-operate-dialog cu-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        @open="onOpen"
        :fullscreen="true"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '':'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <!-- <FormItem :label="t('apply.reimbursement.no')" type="string" v-model="baTable.form.items!.no" prop="no" :placeholder="t('Please input field', { field: t('apply.reimbursement.no') })" /> -->
                    <el-row>
                        <el-col :span="12">
                            <FormItem :label="t('apply.reimbursement.project_id')" type="remoteSelect" v-model="baTable.form.items!.project_id" prop="project_id" :input-attr="{ pk: 'ba_project.id', field: 'title', 'remote-url': '/admin/Project/index' }" :placeholder="t('Please select field', { field: t('apply.reimbursement.project_id') })" />
                        </el-col>
                        <el-col :span="12">
                            <FormItem :label="t('apply.reimbursement.title')" type="string" v-model="baTable.form.items!.title" prop="title" :placeholder="t('Please input field', { field: t('apply.reimbursement.title') })" />
                        </el-col>
                        <el-col :span="12">
                            <FormItem :label="t('apply.reimbursement.date')" type="date" v-model="baTable.form.items!.date" prop="date" :placeholder="t('Please select field', { field: t('apply.reimbursement.date') })" />
                        </el-col>
                        <el-col :span="12">
                            <FormItem :label="t('apply.reimbursement.amount')" type="number" prop="amount" :input-attr="{ step: 1, readonly: true }" v-model.number="baTable.form.items!.amount" :placeholder="t('Please input field', { field: t('apply.reimbursement.amount') })" />
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="付款类目">
                                <div class="" :key="index" v-for="item,index in feeitemSets">
                                    <el-row>
                                        <el-col :span="15">
                                            <el-cascader 
                                                :props="{
                                                    value: 'id',
                                                    label: 'title',
                                                    emitPath: false
                                                }" 
                                                v-model="item.feeitem_id"
                                                :options="feeitemLists" 
                                                :show-all-levels="false" 
                                                :filterable="true"
                                                :placeholder="t('Please select field', { field: t('付款类目') })"
                                                style="width:100%">
                                                </el-cascader>
                                        </el-col>
                                        <el-col :span="6">
                                            <el-input type="number" v-model.number="item.amount" @change="(val) => { feeitemHand(val, 'amount', index) }" placeholder="Please input" />
                                        </el-col>
                                        <el-col :span="3">
                                            <Icon name="el-icon-CirclePlus" color="#409eff" size="26" @click="addFeeitems" v-if="index == feeitemSets?.length -1"/>
                                            <Icon name="el-icon-Remove" color="#f56c6c" size="26" @click="delFeeitems(index)" v-else/>
                                        </el-col>
                                    </el-row>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item :label="t('apply.reimbursement.detail')">
                        <el-table
                            :data="details_lists"
                            style="width: 100%"
                            @cell-click="onCellClick">
                            <el-table-column type="index" width="40" />
                            <el-table-column :key="index" :prop="`f${index}`" :label="item" v-for="item, index in details_headers">
                                <template #default="{ row, column, $index }">
                                    <template v-if="tableEditKey == `${row.id}-${column.property}`">
                                        <el-autocomplete v-model="row[column.property]" size="small" @blur="inputBlur" :fetch-suggestions="(queryString, cd) => { return switchQuerySearch(queryString, cd, column.property) }" clearable id="table-input" v-if="['f9', 'f12'].indexOf(column.property) > -1"/>
                                        <el-input type="text" size="small" ref="inputRef" @blur="inputBlur" @input="inputInput" id="table-input" v-model="row[column.property]" v-else></el-input>
                                    </template>
                                    <template v-else>
                                        <div class="table-input-item">
                                            <el-text>{{row[column.property]}}</el-text>
                                            <!-- <Icon name="fa fa-edit" size="14" color="#ccc"/> -->
                                        </div>
                                    </template>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" width="60" :fixed="'right'" label="操作">
                                <template #default="{ $index }">
                                    <Icon name="el-icon-Delete" color="#F56C6C" size="20"  @click.stop="delDetailItem($index)" style="cursor: pointer;"/>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="add-item">
                            <el-button class="add-btn" :icon="Plus" @click="addDetailItem">添加费用明细</el-button>
                        </div>
                    </el-form-item>
                    <FormItem :label="t('图片')" type="images" v-model="baTable.form.items!.image" prop="image" />
                    <FormItem :label="t('apply.reimbursement.files')" type="files" v-model="baTable.form.items!.files" prop="files" />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="onSubmit" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
interface feeitemSetsItem {
    feeitem_id:number 
    feeitem_name: string
    amount:number
}
import { ElMessage, type FormInstance, type FormItemRule } from 'element-plus'
import { inject, reactive, ref, onMounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'
import { timeFormat } from '/@/utils/common'
import { getFeeitemList } from '/@/api/backend/index'
import { Delete, Plus } from '@element-plus/icons-vue'
import { randomNum } from '/@/utils/random'

const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass
const { t } = useI18n()

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    title: [
        buildValidatorData({ name: 'required', title: t('报销内容') })
    ],
    project_id: [
        buildValidatorData({ name: 'required', title: t('apply.reimbursement.project_id') })
    ],
    date: [
        buildValidatorData({ name: 'required', title: t('apply.reimbursement.date') }),
        buildValidatorData({ name: 'date', title: t('apply.reimbursement.date') })
    ],
    feeitem_id: [
        buildValidatorData({ name: 'required', title: t('apply.reimbursement.feeitem_id') })
    ],
    amount: [
        buildValidatorData({ name: 'required', title: t('apply.reimbursement.date') }),
        buildValidatorData({ name: 'number', title: t('apply.reimbursement.amount') })
    ]
})

let feeitemLists: any[] = [];
let tableEditKey = ref('')
let inputValue = ''
const feeitemSets = ref<feeitemSetsItem[]>()
let feeitemListsAll: any[] = []

const details_headers = ['费用编号', '费用二级', '日期', '事由', '起点', '终点', '金额', '发票', '发票号', '是否抵扣', '抵扣后金额', '附件', '付款状态']
const details_lists = ref([])
onMounted(() => {
    getFeeitemList().then(res => {
        const tempDatas: any[] = []
        res.data.list.forEach((item: any) => {
            feeitemListsAll.push(item)
            tempDatas.push({
                id: item.id,
                title: item.title,
                pid: item.pid,
                disabled: false,
                children: []
            })
            const index = tempDatas.length - 1
            item.children?.forEach((ele: any) => {
                feeitemListsAll.push(ele)
                tempDatas[index]['children'].push({
                    id: ele.id,
                    title: ele.title,
                    pid: ele.pid,
                    disabled: false,
                })
            })
        })
        feeitemLists = tempDatas
    })
})

const onOpen = () => {
    if(!baTable.form.items!.no) baTable.form.items!.date = timeFormat(null, 'yyyy-mm-dd');
    details_lists.value = []
    feeitemSets.value = [{feeitem_id: 0, feeitem_name: '', amount: 0}]
}

const onCellClick = (row: any, column: any, cell: any, event: any) => {
    tableEditKey.value = `${row.id}-${column.property}`
    inputValue = row[column.property]
    nextTick(() => {
        document.getElementById('table-input')?.focus()
    })
}

const inputBlur = (event: FocusEvent) => {
    tableEditKey.value = ``
}

const inputInput = (value: string | number) => {
    let val = value
    const keys = tableEditKey.value.split('-')
    const property = keys[1]
    const index = details_lists.value.findIndex((p: any) => p.id == keys[0])
    details_lists.value[index][property] = val
}

const addDetailItem = () => {
    details_lists.value.push({id: randomNum(10000000,99999999), f0: '', f1: '', f2: '',f3: '',f4: '',f5: '',f6: '',f7: '',f8: '',f9: '',f10: '',f11: '',f12: '',f13: '',f14: '',f15: '',})
}

const delDetailItem = (index) => {
    details_lists.value.splice(index, 1)
}

const switchQuerySearch = (queryString: string, cb: any, field: string) => {
    const dic = {
        'f9': [{value: '是'}, {value: '否'}],
        'f12': [{value: '已付款'}, {value: '未付款'}]
    }
    cb(dic[field])
}

const addFeeitems = () => {
    feeitemSets.value?.push({feeitem_id: 0, feeitem_name: '', amount: 0})
}

const delFeeitems = (index: number)=>{
    feeitemSets.value?.splice(index, 1)
    caclFeeitems()
}

const feeitemHand = (val:string|number, field: string, index: number) => {
    feeitemSets.value[index][field] = val
    caclFeeitems()
}

const caclFeeitems = () => {
    let amount = 0
    feeitemSets.value.forEach((item: feeitemSetsItem) => {
        amount += Number(item.amount)
    })
    baTable.form.items!.amount = amount
}

const onSubmit = () => {
    for(let i = 0; i < feeitemSets.value?.length; i++){
        if(Number(feeitemSets.value[i]['feeitem_id']) <= 0){
            return ElMessage.error(`第${++i}项的费用项目未选择`)
        }
        // if(Number(feeitemSets.value[i]['amount']) <= 0){
        //     return ElMessage.error(`第${++i}项的费用金额不能小于0`)
        // }
    }
    feeitemSets.value?.forEach((item: feeitemSetsItem, index: number) => {
        item.feeitem_name = feeitemListsAll.find((p: any) => p.id == item.feeitem_id)['title']
    })
    baTable.form.items!.feeitems = feeitemSets.value
    baTable.form.items!.detail = details_lists.value
    baTable.onSubmit(formRef.value)
}

</script>

<style lang="scss">
    .el-dialog.cu-dialog.is-fullscreen { overflow: hidden; }
    .el-dialog.cu-dialog.is-fullscreen  .el-dialog__body { height: calc(100vh - 60px);  }
</style>
<style scoped lang="scss">
    .ba-operate-dialog :deep .el-dialog__body { padding-bottom: 0; height: calc(100vh - 100px); }
    .table-input-item { display: flex;
        font-size: 12px;
    justify-content: space-between;
    align-items: center;
    border: 1px dashed #aaa;
    padding-left: 5px;
    height: 25px;
        .el-text { font-size: inherit; }
    }
    .table-input-item:hover { border-color: #999;background-color: #ffffff; }
    .add-item { padding-top: 5px; display: flex; }
    .add-item .add-btn { flex: 1; border: 1px dashed #eee; }
</style>
